package com.su02.multi.util;

import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Objects;

public final class ListUtil {
    private ListUtil() {}

    public static <E> E last(List<E> elems) {
        int sz = CollectionUtils.size(elems);
        if (Objects.equals(sz, 0)) {
            throw new IllegalArgumentException();
        }
        return elems.get(sz - 1);
    }

    public static <E> E exactOne(List<E> elems) {
        int sz = CollectionUtils.size(elems);
        if (!Objects.equals(sz, 1)) {
            throw new IllegalArgumentException();
        }
        return elems.get(0);
    }

    public static <E> E getOrDefault(List<E> elems, int index, E value) {
        if (index < 0) {
            throw new IllegalArgumentException();
        }
        Objects.requireNonNull(value);
        if (index >= CollectionUtils.size(elems)) {
            return value;
        }
        return elems.get(index);
    }
}
